using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;
using System.Security.Claims;

namespace Lzfy_Refund_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class RefundController : ControllerBase
    {
        private readonly IRefundService _refundService;
        private readonly IHisPatientBalanceService _hisPatientBalanceService;
        private readonly IWeChatNotificationService _weChatNotificationService;
        private readonly ILogger<RefundController> _logger;

        public RefundController(
            IRefundService refundService, 
            IHisPatientBalanceService hisPatientBalanceService,
            IWeChatNotificationService weChatNotificationService,
            ILogger<RefundController> logger)
        {
            _refundService = refundService;
            _hisPatientBalanceService = hisPatientBalanceService;
            _weChatNotificationService = weChatNotificationService;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有退费申请
        /// </summary>
        /// <returns>退费申请列表</returns>
        [HttpPost("get-all")]
        public async Task<ActionResult<IEnumerable<RefundResponse>>> GetAllRefunds()
        {
            var refunds = await _refundService.GetAllRefundsAsync();
            return Ok(refunds);
        }

        /// <summary>
        /// 根据ID获取退费申请详情
        /// </summary>
        /// <param name="request">包含退费申请ID的请求</param>
        /// <returns>退费申请详情</returns>
        [HttpPost("get-by-id")]
        public async Task<ActionResult<RefundResponse>> GetRefundById([FromBody] GetByIdRequest request)
        {
            var refund = await _refundService.GetRefundByIdAsync(request.Id);
            if (refund == null)
            {
                return NotFound(new { message = "退费申请不存在" });
            }

            return Ok(refund);
        }

        /// <summary>
        /// 根据关联ID获取退费申请详情
        /// </summary>
        /// <param name="request">包含关联ID的请求</param>
        /// <returns>退费申请详情</returns>
        [HttpPost("get-by-rel-id")]
        public async Task<ActionResult<RefundResponse>> GetRefundByRelId([FromBody] GetByRelIdRequest request)
        {
            var refund = await _refundService.GetRefundByRelIdAsync(request.RelId);
            if (refund == null)
            {
                return NotFound(new { message = "退费申请不存在" });
            }

            return Ok(refund);
        }

        /// <summary>
        /// 根据患者ID获取退费申请列表
        /// </summary>
        /// <param name="request">包含患者ID的请求</param>
        /// <returns>退费申请列表</returns>
        [HttpPost("get-by-patient")]
        public async Task<ActionResult<IEnumerable<RefundResponse>>> GetRefundsByPatientId([FromBody] GetByPatientIdRequest request)
        {
            var refunds = await _refundService.GetRefundsByPatientIdAsync(request.PatientId);
            return Ok(refunds);
        }

        /// <summary>
        /// 根据患者ID和时间范围获取退费申请列表
        /// </summary>
        /// <param name="request">包含患者ID和查询天数的请求</param>
        /// <returns>退费申请列表</returns>
        [HttpPost("get-by-patient-and-date-range")]
        public async Task<ActionResult<IEnumerable<RefundResponse>>> GetRefundsByPatientIdAndDateRange([FromBody] GetByPatientIdAndDateRangeRequest request)
        {
            if (request.Days <= 0)
            {
                return BadRequest(new { message = "查询天数必须大于0" });
            }
            
            var refunds = await _refundService.GetRefundsByPatientIdAndDateRangeAsync(request.PatientId, request.Days);
            return Ok(refunds);
        }

        /// <summary>
        /// 获取带过滤条件的退费申请
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>退费申请列表</returns>
        [HttpPost("get-with-filter")]
        public async Task<IActionResult> GetRefundsWithFilter([FromBody] RefundQueryRequest request)
        {
            try
            {
                var response = await _refundService.GetRefundsWithFilterAsync(request);
                return Ok(response);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "获取退款数据失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取退费申请统计数据
        /// </summary>
        /// <param name="request">统计查询请求</param>
        /// <returns>统计数据响应</returns>
        [HttpPost("statistics")]
        public async Task<IActionResult> GetRefundStatistics([FromBody] StatisticsQueryRequest request)
        {
            try
            {
                // 验证分页参数
                if (request.PageIndex <= 0)
                {
                    request.PageIndex = 1;
                }
                
                if (request.PageSize <= 0 || request.PageSize > 100)
                {
                    request.PageSize = 20;
                }

                // 验证日期范围
                if (request.StartDate.HasValue && request.EndDate.HasValue && request.StartDate > request.EndDate)
                {
                    return BadRequest(new { message = "开始日期不能大于结束日期" });
                }

                var result = await _refundService.GetRefundStatisticsAsync(request);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = "获取统计数据失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 创建退费申请
        /// </summary>
        /// <param name="request">退费申请创建请求</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public async Task<ActionResult> CreateRefund([FromBody] RefundMasterCreateRequest request)
        {
            if (request.Attachments == null || !request.Attachments.Any())
            {
                return BadRequest(new { success = false, message = "至少需要上传一个附件" });
            }

            try
            {
                var refundId = await _refundService.CreateRefundAsync(request);
                
                // 发送微信推送通知（异步执行，不影响主流程）
                _ = Task.Run(async () =>
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(request.PatientId))
                        {
                            var notificationResult = await _weChatNotificationService.SendRefundSubmittedNotificationAsync(request.PatientId, refundId);
                            if (notificationResult.Success)
                            {
                                _logger.LogInformation($"退费申请提交成功通知已发送 - 患者ID: {request.PatientId}, 退费ID: {refundId}");
                            }
                            else
                            {
                                _logger.LogWarning($"退费申请提交成功通知发送失败 - 患者ID: {request.PatientId}, 退费ID: {refundId}, 原因: {notificationResult.Message}");
                            }
                        }
                        else
                        {
                            _logger.LogWarning($"患者ID为空，跳过微信通知发送 - 退费ID: {refundId}");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"发送退费申请提交成功通知时发生异常 - 患者ID: {request.PatientId}, 退费ID: {refundId}");
                    }
                });
                
                return Ok(new { success = true, data = new { id = refundId }, message = "退费申请创建成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新退费申请
        /// </summary>
        /// <param name="id">退费申请ID</param>
        /// <param name="request">退费申请更新请求</param>
        /// <returns>更新结果</returns>
        [HttpPut("{id}")]
        public async Task<ActionResult> UpdateRefund(int id, [FromBody] RefundMasterCreateRequest request)
        {
            try
            {
                var success = await _refundService.UpdateRefundAsync(id, request);
                if (!success)
                {
                    return NotFound(new { message = "退费申请不存在" });
                }

                return Ok(new { message = "更新成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = "更新退费申请失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 删除退费申请
        /// </summary>
        /// <param name="id">退费申请ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteRefund(int id)
        {
            try
            {
                var success = await _refundService.DeleteRefundAsync(id);
                if (!success)
                {
                    return NotFound(new { message = "退费申请不存在" });
                }

                return Ok(new { message = "删除成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = "删除退费申请失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 审核退费申请
        /// </summary>
        /// <param name="id">退费申请ID</param>
        /// <param name="request">审核请求</param>
        /// <returns>审核结果</returns>
        [HttpPatch("{id}/audit")]
        public async Task<ActionResult> AuditRefund(int id, [FromBody] RefundMasterUpdateRequest request)
        {
            try
            {
                // 从JWT token中获取用户信息
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                var userName = User.FindFirst(ClaimTypes.Name)?.Value;
                var fullName = User.FindFirst("full_name")?.Value;
                
                // 设置审核人信息
                request.AuditUserId = userId;
                request.AuditUserName = fullName ?? userName;

                var updatedRefund = await _refundService.AuditRefundAsync(id, request);
                if (updatedRefund == null)
                {
                    return NotFound(new { message = "退费申请不存在" });
                }

                // 发送微信推送通知（异步执行，不影响主流程）
                _ = Task.Run(async () =>
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(updatedRefund.PatientId))
                        {
                            WeChatNotificationResult notificationResult;
                            
                            if (request.AuditResult == "1")
                            {
                                notificationResult = await _weChatNotificationService.SendRefundApprovedNotificationAsync(updatedRefund.PatientId, id);
                                if (notificationResult.Success)
                                {
                                    _logger.LogInformation($"退费审核通过通知已发送 - 患者ID: {updatedRefund.PatientId}, 退费ID: {id}");
                                }
                                else
                                {
                                    _logger.LogWarning($"退费审核通过通知发送失败 - 患者ID: {updatedRefund.PatientId}, 退费ID: {id}, 原因: {notificationResult.Message}");
                                }
                            }
                            else if (request.AuditResult == "2")
                            {
                                notificationResult = await _weChatNotificationService.SendRefundRejectedNotificationAsync(updatedRefund.PatientId, id, request.AuditComment ?? "审核未通过");
                                if (notificationResult.Success)
                                {
                                    _logger.LogInformation($"退费审核拒绝通知已发送 - 患者ID: {updatedRefund.PatientId}, 退费ID: {id}");
                                }
                                else
                                {
                                    _logger.LogWarning($"退费审核拒绝通知发送失败 - 患者ID: {updatedRefund.PatientId}, 退费ID: {id}, 原因: {notificationResult.Message}");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"发送退费审核通知时发生异常 - 退费ID: {id}");
                    }
                });

                return Ok(new { message = "审核成功", data = updatedRefund });
            }
            catch (ArgumentException ex)
            {
                return NotFound(new { message = ex.Message });
            }
            catch (InvalidOperationException ex)
            {
                return Conflict(new { message = ex.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "审核退费申请时发生未知异常 - 退费ID: {RefundId}", id);
                return BadRequest(new { message = "审核退费申请失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取患者HIS系统余额
        /// </summary>
        /// <param name="patientId">患者ID</param>
        /// <returns>患者余额</returns>
        [HttpGet("patient-balance/{patientId}")]
        public async Task<ActionResult> GetPatientBalance(string patientId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(patientId))
                {
                    return BadRequest(new { message = "患者ID不能为空" });
                }

                var balance = await _hisPatientBalanceService.GetPatientBalanceAsync(patientId);
                
                return Ok(new { 
                    success = true, 
                    data = new { 
                        patientId = patientId,
                        balance = balance ?? 0
                    },
                    message = "获取患者余额成功" 
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { 
                    success = false, 
                    message = "获取患者余额失败", 
                    error = ex.Message 
                });
            }
        }

        /// <summary>
        /// 分页获取退费申请
        /// </summary>
        /// <param name="pageNumber">页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <param name="auditResult">审核结果</param>
        /// <param name="settleStatus">结算状态</param>
        /// <param name="bankCardHolder">银行卡持有人</param>
        /// <param name="auditUserName">审核人</param>
        /// <returns>分页退费申请列表</returns>
        [HttpGet("paged")]
        public async Task<ActionResult> GetRefundsPaged(
            [FromQuery] int pageNumber = 1,
            [FromQuery] int pageSize = 20,
            [FromQuery] string? startDate = null,
            [FromQuery] string? endDate = null,
            [FromQuery] string? auditResult = null,
            [FromQuery] string? settleStatus = null,
            [FromQuery] string? bankCardHolder = null,
            [FromQuery] string? auditUserName = null)
        {
            try
            {
                // 验证分页参数
                if (pageNumber <= 0) pageNumber = 1;
                if (pageSize <= 0 || pageSize > 100) pageSize = 20;

                DateTime? start = null;
                DateTime? end = null;

                // 解析日期参数
                if (!string.IsNullOrEmpty(startDate) && DateTime.TryParse(startDate, out var startDateTime))
                {
                    start = startDateTime;
                }
                if (!string.IsNullOrEmpty(endDate) && DateTime.TryParse(endDate, out var endDateTime))
                {
                    end = endDateTime.AddDays(1).AddSeconds(-1); // 包含整天
                }

                var result = await _refundService.GetRefundsPagedAsync(pageNumber, pageSize, start, end, auditResult, settleStatus, bankCardHolder, auditUserName);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "获取退费数据失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 批量结算退费申请
        /// </summary>
        /// <param name="request">批量结算请求</param>
        /// <returns>结算结果</returns>
        [HttpPost("batch-settle")]
        public async Task<ActionResult> BatchSettle([FromBody] BatchSettleRequest request)
        {
            try
            {
                if (request.RefundIds == null || !request.RefundIds.Any())
                {
                    return BadRequest(new { message = "请选择要结算的退费记录" });
                }

                // 添加调试日志
                Console.WriteLine($"[DEBUG] BatchSettle接收到的参数 - OperatorName: {request.OperatorName}, OperatorFullName: {request.OperatorFullName}");

                // 优先使用前端传递的用户信息，如果没有则从JWT token中获取
                string operatorName;
                string operatorFullName;
                
                if (!string.IsNullOrWhiteSpace(request.OperatorName) && !string.IsNullOrWhiteSpace(request.OperatorFullName))
                {
                    // 使用前端传递的用户信息
                    operatorName = request.OperatorName;
                    operatorFullName = request.OperatorFullName;
                }
                else
                {
                    // 从JWT token中获取用户信息作为备选
                    var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                    var userName = User.FindFirst(ClaimTypes.Name)?.Value;
                    var fullName = User.FindFirst("full_name")?.Value;

                    operatorName = userName ?? "系统";
                    operatorFullName = !string.IsNullOrWhiteSpace(fullName) ? fullName : 
                                     !string.IsNullOrWhiteSpace(userName) ? userName : "系统";
                }

                var result = await _refundService.BatchSettleAsync(request.RefundIds, operatorName, operatorFullName);
                
                return Ok(new { 
                    success = true, 
                    data = result,
                    message = $"成功结算 {request.RefundIds.Count} 条记录" 
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { 
                    success = false, 
                    message = "批量结算失败", 
                    error = ex.Message 
                });
            }
        }

        /// <summary>
        /// 根据结算ID获取退费申请列表
        /// </summary>
        /// <param name="acctId">结算ID</param>
        /// <returns>退费申请列表</returns>
        [HttpGet("by-acct-id/{acctId}")]
        public async Task<ActionResult> GetRefundsByAcctId(string acctId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(acctId))
                {
                    return BadRequest(new { message = "结算ID不能为空" });
                }

                var refunds = await _refundService.GetRefundsByAcctIdAsync(acctId);
                return Ok(new { 
                    success = true, 
                    data = refunds,
                    message = "获取退费申请列表成功" 
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { 
                    success = false, 
                    message = "获取退费申请列表失败", 
                    error = ex.Message 
                });
            }
        }

        /// <summary>
        /// 更新HIS退费状态
        /// </summary>
        /// <param name="request">更新HIS退费状态请求</param>
        /// <returns>更新结果</returns>
        [HttpPost("update-his-refund-status")]
        public async Task<ActionResult> UpdateHisRefundStatus([FromBody] UpdateHisRefundStatusRequest request)
        {
            try
            {
                var success = await _refundService.UpdateHisRefundStatusAsync(request.Id, request.HisRefundStatus);
                
                if (success)
                {
                    return Ok(new { 
                        success = true, 
                        message = "HIS退费状态更新成功" 
                    });
                }
                else
                {
                    return BadRequest(new { 
                        success = false, 
                        message = "HIS退费状态更新失败" 
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新HIS退费状态失败，ID: {Id}, Status: {Status}", request.Id, request.HisRefundStatus);
                return BadRequest(new { 
                    success = false, 
                    message = "更新HIS退费状态失败", 
                    error = ex.Message 
                });
            }
        }
    }
}